package opa

import (
	"context"
	"log"
	"os"

	"github.com/open-policy-agent/opa/rego"
)

var (
	policyPath   = "/etc/robot/rbac.rego"
	defaultQuery = "x = data.rbac.allow"
)

func ReadPolicy(path string) ([]byte, error) {
	policy, err := os.ReadFile(path)
	if err != nil {
		log.Fatalf("can't read policy file: %v", err)
	}
	return policy, nil
}

func ReadOpa(policpath string) (rego.PreparedEvalQuery, error) {
	p, err := ReadPolicy(policyPath)
	if err != nil {
		return rego.PreparedEvalQuery{}, err
	}
	ctx := context.TODO()
	return rego.New(rego.Query(defaultQuery), rego.Module(policyPath, string(p))).PrepareForEval(ctx)
}

func Authizator(ctx context.Context, ped rego.PreparedEvalQuery, input interface{}) (bool, error) {
	results, err := ped.Eval(ctx, rego.EvalInput(input))
	if err != nil {
		log.Fatalf("evaluation error: %v", err)
		return false, err
	} else if len(results) == 0 {
		log.Fatal("undefined result", err)
		// Handle undefined result.
		return false, nil
	} else if result, ok := results[0].Bindings["x"].(bool); !ok {
		log.Fatalf("unexpected result type: %v", result)
		return false, nil
	}
	return results[0].Bindings["x"].(bool), nil
}
